package org.bunny.vehicle.service;

import java.net.URLEncoder;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bunny.vehicle.entity.User;
import org.bunny.vehicle.repository.ExpenseRepository;
import org.bunny.vehicle.repository.JourneyRepository;
import org.bunny.vehicle.repository.UserRepository;
import org.bunny.vehicle.repository.VehicleRepository;
import org.bunny.vehicle.util.Const;
import org.directwebremoting.WebContextFactory;

import com.alibaba.fastjson.JSONObject;

public abstract class BaseService {

	protected static final Log log = LogFactory.getLog(BaseService.class);

	@Resource
	protected UserRepository userRepository;

	@Resource
	protected VehicleRepository vehicleRepository;

	@Resource
	protected JourneyRepository journeyRepository;

	@Resource
	protected ExpenseRepository expenseRepository;

	protected User getUser() {
		return (User) getSessionAttribute(Const.SESSION_USER);
	}

	protected void setCookie(String name, Object value, int maxAge) {
		HttpServletResponse response = WebContextFactory.get().getHttpServletResponse();
		HttpServletRequest request = WebContextFactory.get().getHttpServletRequest();
		try {
			String json = value == null ? "" : URLEncoder.encode(JSONObject.toJSONString(value),
					Const.CHARSET);
			Cookie cookie = new Cookie(name, json);
			cookie.setPath(request.getContextPath() + "/");
			cookie.setMaxAge(maxAge);
			response.addCookie(cookie);
		} catch (Exception e) {
			log.error(e);
		}
	}

	protected Object getSessionAttribute(String name) {
		HttpSession session = WebContextFactory.get().getSession(false);
		if (null != session) {
			return session.getAttribute(name);
		}
		return null;
	}

	protected void setSessionAttribute(String name, Object value) {
		HttpSession session = WebContextFactory.get().getSession();
		session.setAttribute(name, value);
	}

}
